#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "TZImagePickerController.h"
#import <RXSDK_Pure/RXSDK_Pure.h>

@interface AppDelegate () <FlutterStreamHandler>
@property(nonatomic, strong) FlutterEventSink eventSink;

@property (nonatomic, strong) NSMutableArray *selectedPhotos;//选择的图片数组
@property (nonatomic, strong) NSMutableArray *selectedAssets;//选择的资源数组
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
    // 获取 FlutterViewController
  FlutterViewController *flutterViewController = (FlutterViewController*)self.window.rootViewController;
  RuiXueApiSetup(flutterViewController.binaryMessenger, self);
  
  FlutterEventChannel* eventChannel = [FlutterEventChannel eventChannelWithName:@"image_picker_upload_progress" binaryMessenger:flutterViewController.binaryMessenger];
  [eventChannel setStreamHandler:self];
    
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)initSdkWithCompletion:(void (^)(ResponseData * _Nullable, FlutterError * _Nullable))completion
{
    RXSdkInitConfig *config = [[RXSdkInitConfig alloc] init];
    config.productId = @"1002";
    config.channelId = @"100";
    config.cpId = @"114";
    config.baseUrlList = @[@"https://cn-api-test.ruixueyun.com"];
    [[RXService sharedSDK] initWithConfig:config complete:^(NSDictionary * _Nullable response, RX_CommonRequestError * _Nullable error) {
            if (!error) {
                NSLog(@"初始化成功");
                ResponseData *response = [[ResponseData alloc] init];
                response.code = @(0);
                response.message = @"RXSDK init success";
                if (completion) {
                    completion(response, nil);
                }
            } else {
                NSLog(@"初始化失败");
                ResponseData *response = [[ResponseData alloc] init];
                if (error.responesObject) {
                    @try {
                        response.code = error.responesObject[@"code"];
                        response.message = error.responesObject[@"msg"];
                    } @catch (NSException *exception) {
                        response.code = @(1);
                        response.message = @"";
                    }
                } else {
                    response.code = @(1);
                    response.message = @"";
                }
                if (completion) {
                    completion(response, nil);
                }
            }
    }];
}

- (void)ossUploadObjectKey:(NSString *)objectKey filePath:(NSString *)filePath completion:(void (^)(ResponseData * _Nullable, FlutterError * _Nullable))completion
{
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    [[RXOSSPutManager sharedSDK] uploadWithBodyData:fileData ossPath:objectKey process:^(float process) {
        NSLog(@"WLTest upload process %@", @(process));
        if (self.eventSink) {
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
            dict[@"objectKey"] = objectKey;
            dict[@"progress"] = @(process);
            self.eventSink(dict);
        }
        } complete:^(NSDictionary * _Nullable response, RX_CommonRequestError * _Nullable error) {
            if (!error) {
                NSLog(@"上传成功");
                if (response) {
                    NSString* data = [self toJSONString:response];
                    ResponseData *response = [[ResponseData alloc] init];
                    response.code = @(0);
                    response.message = @"";
                    response.data = data;
                    if (completion) {
                        completion(response, nil);
                    }
                } else {
                    NSLog(@"上传成功 but response null");
                    ResponseData *response = [[ResponseData alloc] init];
                    response.code = @(1);
                    response.message = @"";
                    if (completion) {
                        completion(response, nil);
                    }
                }
            } else {
                ResponseData *response = [[ResponseData alloc] init];
                if (error.responesObject) {
                    @try {
                        response.code = error.responesObject[@"code"];
                        response.message = error.responesObject[@"msg"];
                    } @catch (NSException *exception) {
                        response.code = @(1);
                        response.message = @"";
                    }
                } else {
                    response.code = @(1);
                    response.message = @"";
                }
                if (completion) {
                    completion(response, nil);
                }
            }
        }];
}


- (NSMutableArray *)selectedPhotos{
    if (!_selectedPhotos) {
        _selectedPhotos = [[NSMutableArray alloc] init];
    }
    return _selectedPhotos;
}

- (NSMutableArray *)selectedAssets{
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc] init];
    }
    return _selectedAssets;
}

- (void)launchNativePhotoMap:(NSDictionary<NSString *,id> *)map completion:(void (^)(ResponseData * _Nullable, FlutterError * _Nullable))completion
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    
    imagePickerVc.selectedAssets = self.selectedAssets;
    imagePickerVc.alwaysEnableDoneBtn = YES;
    
    imagePickerVc.allowTakePicture = NO; //是否允许拍照
    imagePickerVc.allowCrop = YES; //是否裁剪
    
    imagePickerVc.allowPickingVideo = YES; //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = YES;
    
    imagePickerVc.allowTakeVideo = NO; // 在内部显示拍视频按
    imagePickerVc.allowEditVideo = NO; // 允许编辑视频
    imagePickerVc.presetName = AVAssetExportPresetLowQuality; // 编辑后的视频的导出质量
    __weak typeof(self) weakSelf = self;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];
        for (int i = 0 ; i < weakSelf.selectedPhotos.count; i ++) {
            UIImage* image = weakSelf.selectedPhotos[i];
            
            PHAsset *asset = weakSelf.selectedAssets[i];
            NSString *type = @"";
            if (asset.mediaType == PHAssetMediaTypeImage) {
                type = @"image";
            } else if (asset.mediaType == PHAssetMediaTypeVideo) {
                type = @"video";
            }
            NSLog(@"media type:%@ location:%@",type, asset.localIdentifier);
            //TODO by chenhan 这里如何获取到 /private/var/****.png 这种绝对目录传递个 flutter
//            model.asset = asset;
//            if (asset.mediaType == PHAssetMediaTypeImage) {
//                model.type = @"image";
//            } else if (asset.mediaType == PHAssetMediaTypeVideo) {
//                model.type = @"video";
//            }
//            [weakSelf.selectModelArray addObject:model];
        }
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [[self currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
}

/** 返回当前控制器 */
- (UIViewController *)currentViewController {
    
    UIViewController *rootViewController = self.window.rootViewController;
    return [self currentViewControllerFrom:rootViewController];
}

- (UIViewController *)currentViewControllerFrom:(UIViewController*)viewController {
    
    // 如果传入的控制器是导航控制器,则返回最后一个
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        
        UINavigationController *navigationController = (UINavigationController *)viewController;
        return [self currentViewControllerFrom:navigationController.viewControllers.lastObject];
    }
    // 如果传入的控制器是tabBar控制器,则返回选中的那个
    else if([viewController isKindOfClass:[UITabBarController class]]) {
        
        UITabBarController *tabBarController = (UITabBarController *)viewController;
        return [self currentViewControllerFrom:tabBarController.selectedViewController];
    }
    // 如果传入的控制器发生了modal,则就可以拿到modal的那个控制器
    else if(viewController.presentedViewController != nil) {
        return [self currentViewControllerFrom:viewController.presentedViewController];
    }
    else {
        return viewController;
    }
}


- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events
{
    self.eventSink = events;
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
    self.eventSink = nil;
    return nil;
}

- (NSString *)toJSONString:(NSDictionary *) dict
{
    // 将 NSDictionary 转换为 JSON 数据
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                      options:NSJSONWritingPrettyPrinted
                                                        error:&error];
    
    // 检查是否转换成功
    if (!jsonData) {
        NSLog(@"Error converting dictionary to JSON: %@", error.localizedDescription);
        return nil;
    } else {
        // 将 JSON 数据转换为 NSString
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String: %@", jsonString);
        return jsonString;
    }
}

@end
